package com.osgix.common.utils;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.ObjectMapper;

public class JsonUtils {
	/**
	 * 生成Json string
	 * 
	 * @param obj
	 * @return
	 * @throws IOException
	 */
	public static String generateJson(Object obj) throws IOException {
		ObjectMapper mapper = new ObjectMapper();
		StringWriter sw = new StringWriter();
		JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);
		mapper.writeValue(gen, obj);
		gen.close();
		String objJsonStr = sw.getBuffer().toString();
		System.out.println(">>>" + objJsonStr);
		return objJsonStr;
	}

	public static Object parseJson(String json) throws JsonParseException, IOException {
		// MappingJsonFactory mjf = new MappingJsonFactory();
		JsonFactory jsonFactory = new JsonFactory(); // or, for data binding,
														// org.codehaus.jackson.mapper.MappingJsonFactory
		JsonParser jp = jsonFactory.createJsonParser(json); // or URL, Stream,
															// Reader, String,
															// byte[]
		ObjectMapper mapper = new ObjectMapper();
		Object obj = mapper.readValue(json, Object.class);
		return obj;
	}

	public static void main(String[] args) {
		/*
		 * Map ss = new HashMap(); ss.put("adsf", new Date(131231231L)); String
		 * jj = null; try { jj = generateJson(ss); } catch (IOException e) {
		 * e.printStackTrace(); } System.out.println(jj);
		 */

		try {
			Object ob = parseJson("\"key\":\"1970-01-02\"");
			Map ss = (Map) ob;
			System.out.println(ss.get("key"));
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
